package utils

import (
	"bytes"
	"encoding/json"
	"net/http"
	"fmt"
)

type DingtalkMessage struct {
	MessageType string    `json:"msgtype"`
	Text        *Text     `json:"text,omitempty"`
	Link        *Link     `json:"link,omitempty"`
	Markdown    *Markdown `json:"markdown,omitempty"`
	At          *At       `json:"at,omitempty"`
}

type Text struct {
	Content string `json:"content"`
}

type Link struct {
	Title      string `json:"title"`
	Text       string `json:"text"`
	MessageURL string `json:"messageUrl"`
	PictureURL string `json:"picUrl,omitempty"`
}

type Markdown struct {
	Title string `json:"title"`
	Text  string `json:"text"`
}

type At struct {
	IsAtAll   bool     `json:"isAtAll,omitempty"`
	AtMobiles []string `json:"atMobiles,omitempty"`
}

type Dingtalk struct {
	DingtalkURL string
	DingtalkName string
}

func (d *Dingtalk) SenMessage(message *DingtalkMessage) error {
	body, err := json.Marshal(&message)
	if err != nil {
		return err
	}

	client := &http.Client{}

	reqest, err := http.NewRequest("POST", d.DingtalkURL, bytes.NewReader(body))
	if err != nil {
		return err
	}

	reqest.Header.Set("Content-Type", "application/json")

	req, err := client.Do(reqest)
	if err != nil {
		return err
	}
    fmt.Println("【" + d.DingtalkName + "】告警信息发送成功!")
	defer req.Body.Close()

	return nil
}

func (d *Dingtalk) SenText(content string, isAtAll bool, mobiles ...string) error {
	return d.SenMessage(&DingtalkMessage{
		MessageType: "text",
		Text:        &Text{content},
		At: &At{
			isAtAll,
			mobiles,
		},
	})
}

func (d *Dingtalk) SenLink(title, text, messageUrl, picUrl string) error {
	return d.SenMessage(&DingtalkMessage{
		MessageType: "link",
		Link: &Link{
			title,
			text,
			messageUrl,
			picUrl,
		},
	})
}

func (d *Dingtalk) SenMarkdown(title, text string) error {
	return d.SenMessage(&DingtalkMessage{
		MessageType: "markdown",
		Markdown: &Markdown{
			title,
			text,
		},
	})
}
